<?php
class Block_Plugin_Block extends Zend_Controller_Plugin_Abstract {
	public function postDispatch(Zend_Controller_Request_Abstract $request) {
		if (! $request->isXmlHttpRequest () && (! $request->isDispatched () || $request->getControllerName () != "error")) {
			
			$params = $request->getParams ();
			$url = $_SERVER ['REQUEST_URI'];
			
			if ((! preg_match ( '/^\/backend/', $url )) && 
				(! preg_match ( '/^\/admin/', $url ))&& 
				(! preg_match ( '/^\/login/', $url ))&& 
				(! preg_match ( '/^\/logout/', $url ))&& 
				(! preg_match ( '/^\/profile/', $url )))
				{
				$url = preg_replace ( '/\/$/', '', $url );
				$url = $url . '/';
				$this->_layout = Zend_Layout::getMvcInstance ();
				$this->_view = $this->_layout->getView ();
				$block_list = new Block_Model_Blocks ();
				$cnf = Zend_Registry::get ( 'cnf' );
				
				$resp = $this->getResponse ();
				$ex = $resp->getException ();
				/*
            * Кеширование блоков
            */
				//TODO Подумать над id для кеширования блоков
				

				$options = array ();
				
				$block_rights = new Block_Model_Rights();
				$find = $block_rights->select ()->getData();
				if ($find) {
					$allow = array ();
					$deny = array ();
					foreach ( $find as $rights ) {
						$urls = explode ( ',', $rights ['url'] );
						if (sizeof ( $urls ) > 0) {
							foreach ( $urls as $blockurl ) {
								
								if (($blockurl != "")&&($blockurl!="{main}")) {
									if (! preg_match ( '/\\*$/', $blockurl )) {
										$blockurl = preg_replace ( '/\/$/', '', $blockurl );
										$blockurl = $blockurl . "/";
									}
									
									$blockurl = preg_replace ( '/\//', '\/', $blockurl );
									$blockurl = preg_replace ( '/\*/', '.*', $blockurl );
									
									
									$blockurl = "\\/" . $blockurl;
									
									if (preg_match ( '/^' . $blockurl . '$/', $url )) {
										
										if ($rights ['allow'] == 1)
										{$allow [$rights ['block_id']] = $rights ['block_id'];}
										else {
											if(!isset($allow [$rights ['block_id']])){
												$deny [$rights ['block_id']] = $rights ['block_id'];
											}
											
										}
									}
								}else{
									if($url=='/'){
										if ($rights ['allow'] == 1){
											$allow [$rights ['block_id']] = $rights ['block_id'];
										}
										else {
											$deny [$rights ['block_id']] = $rights ['block_id'];
										}
									}
								}
								
							}
						}
					}
					
					$blocks = new Block_Model_Blocks();
					$blocks=$blocks->getTable();
					$all = array_diff ( $allow, $deny );
					if (sizeof ( $all ) > 0) {
						$options = $blocks->select ()->order ( 'weight' );
						$in = implode ( ',', $all );
						$date = date ( 'Y-m-d' );
						$options->where ( 'id IN(' . $in . ')' )->where ( "`active`=1 and ((`date_start`<='" . $date . "') or `date_start` is NULL ) and ((`date_end` >='" . $date . "') or `date_end` is NULL )" );
						$options = $options->query ()->fetchAll ();
					}
					
					if (sizeof ( $options ) > 0) {
						$params_common = $params;
						foreach ( $options as $key => $block ) {
							
							$params = $params_common;
							
							if ($block ['params'] != "") {
								$params = array_merge($params, unserialize ( $block ['params'] ) );
							} 
							
							$cont = false;
							if ($block ['cache'] == 1) {
								$cache_id = "block_" . $block ['id'] . md5 ( $url );
								$cont = $block_list->getCache()->load ( $cache_id );
							}
							if ($cont == false) {
								try {
									$cont = $this->_view->action ( $block ['mvc_action'], $block ['mvc_controller'], $block ['mvc_module'], $params );
								
								} catch ( Exception $e ) {
									echo $e;
									$cont = $e->getMessage ();
								}
								if ($block ['cache'] == 1) {
									$block_list->getCache()->save ( $cont, $cache_id, array ('block' ) );
								}
							}
							
							$regions = explode ( ',', $block ['region'] );
							
							foreach ( $regions as $region ) {
								if ($region != "content") {
									$content = $this->_layout->{$region};
									$content .= $cont;
									$this->_layout->assign ( $region, $content );
								} else {
									$content = $resp->getBody ();
									if ($block ['weight'] > 10) { 
										$content .= $cont;
									} else {
										$content = $cont.$content;
									}
									$resp->setBody ( $content );
								}
							}
						}
					}
				}
			}
		}
	}

}